
import { registerClass } from "../../../cfw/tools/class_decorator";
import BaseAd from "../../core/base/BaseAd";
import { SDKLogicState, SDKState } from "../../SDKDefine";


/**
https://minigame.vivo.com.cn/documents/#/api/ad/ban_ner_A_d
1031标准开始支持，低版本需做兼容处理。
banner广告实例不能复用，每次需要重新加载时要重新create
 */
@registerClass('VivoBannerAd')
export default class VivoBannerAd extends BaseAd {

    protected name: string = "VivoBannerAd"


    init(): void {
        this.preload();
    }

    open(): void {
        this.setLogicState(SDKLogicState.open)
        if (this.isState(SDKState.loadSucess)) {
            this.show()
        } else {
            this.create();
        }
    }
    close(): void {
        this.setState(SDKState.close)
        if (this.ad) {
            this.ad.hide();
        }
    }

    show(): void {
        this.setState(SDKState.show)
        this.setLogicState(SDKLogicState.close)
        if (this.ad) {
            this.ad.show();
        }
    }

    getStyle() {
        return {
        }
    }

    protected onLoadLogic(): void {
        if (this.isLogicState(SDKLogicState.open)) {
            this.show()
        }
    }

    updateSize() {

    }

    onResize(data: { width: number, height: number }) {
        // console.log(' banner onResize ', data)
        this.style.width = data.width;
        this.style.height = data.height;
        this.updateSize()
    }



    create() {
        this.destroy()
        this.setState(SDKState.loading)
        if (!this.ad) {
            this.ad = this.sdk.createBannerAd({
                posId: this.adUnitID,
                style: this.getStyle(),
                adIntervals: 30
            })
            this.ad.onLoad(this.onLoad.bind(this))
            this.ad.onError(this.onError.bind(this))
            this.ad.onSize(this.onResize.bind(this))
        }
    }

    destroy(): void {
        console.log(' banner destroy', this.ad)
        this.setState(SDKState.destroy)
        if (this.ad) {
            this.ad.offLoad(this.getFunc(this.onLoad))
            this.ad.offError(this.getFunc(this.onError))
            this.ad.offResize(this.getFunc(this.onResize))
            this.ad.destroy();
            this.ad = null;
        }
    }
}